package com.codinghero.zqlb.spider;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.codinghero.util.ArrayUtils;
import com.codinghero.util.DateUtils;
import com.codinghero.zqlb.match.SoccerMatch;
import com.codinghero.zqlb.spider.handler.ChannelFilterHandler;
import com.codinghero.zqlb.spider.handler.FilterHandler;
import com.codinghero.zqlb.spider.handler.FocusHandler;
import com.codinghero.zqlb.spider.handler.JunkFilterHandler;
import com.sina.sae.fetchurl.SaeFetchurl;

public class ZZBSpider {

	public List<SoccerMatch> parse(String url, String encoding) {
		try {
			SaeFetchurl fetchUrl = new SaeFetchurl();
			String content = fetchUrl.fetch(url);
			content = new String(content.getBytes("ISO-8859-1"), encoding);
			Parser parser = Parser.createParser(content, encoding);
			NodeFilter liFilter = new TagNameFilter("li");
			NodeFilter divFilter = new TagNameFilter("div");
			NodeFilter titlebarFilter = new HasAttributeFilter("class",
					"titlebar");
			NodeFilter matchDateFilter = new AndFilter(divFilter,
					titlebarFilter);
			NodeFilter allFilter = new OrFilter(liFilter, matchDateFilter);

			//
			NodeList nodeList = parser.parse(allFilter);
			List<SoccerMatch> matchList = new ArrayList<SoccerMatch>();
			int year = Integer.parseInt(DateUtils.getCurYear());
			int month = -1;
			int day = -1;
			for (int i = 0; i < nodeList.size(); i++) {
				try {
					String rawStr = nodeList.elementAt(i).getChildren()
							.asString();
					// \r\n不能被.匹配到
					rawStr = rawStr.replace("\r", " ");
					rawStr = rawStr.replace("\n", " ");
					rawStr = rawStr.trim();
					// M月d日
					if (rawStr.matches("^.*[0-9]{1,2}月[0-9]{1,2}日.*$")) {
						int monthIndex = rawStr.indexOf("月");
						String nextMonthStr = rawStr.substring(0, monthIndex);
						String nextDayStr = rawStr.substring(monthIndex + 1,
								rawStr.indexOf("日"));
						int nextMonth = Integer.parseInt(nextMonthStr);
						int nextDay = Integer.parseInt(nextDayStr);

						// 上一天是12月31日，下一天是1月1日，year加1
						if (nextMonth < month)
							year++;
						month = nextMonth;
						day = nextDay;
					}
					// HH:mm 中超 北京国安 - 上海申花 ……
					else if (rawStr.matches("^.*[0-9]{1,2}:[0-9]{1,2}.*$")) {
						String[] rawArr = rawStr.split("[ \t]+");
						if (rawArr == null || rawArr.length < 5)
							continue;
						else {
							// HH:mm
							SoccerMatch match = new SoccerMatch();

							if (rawArr[0].contains("-"))
								rawArr[0] = rawArr[0].substring(0,
										rawArr[0].indexOf("-"));
							int colonIndex = rawArr[0].indexOf(":");
							int hour = Integer.parseInt(rawArr[0].substring(0,
									colonIndex));
							int minute = Integer.parseInt(rawArr[0].substring(
									colonIndex + 1, rawArr[0].length()));
							Calendar c = new GregorianCalendar();
							c.set(year, month - 1, day, hour, minute, 0);
							match.setStartDate(c.getTime());

							// 1比赛名称，2主队名称，4客队名称
							match.setTypeName(rawArr[1]);
							match.setTeam1Name(rawArr[2]);
							match.setTeam2Name(rawArr[4]);
							match.setChannelNameList(ArrayUtils.toList(rawArr,
									5, rawArr.length - 1));
							matchList.add(match);
						}
					}
				} catch (Exception e) {
					System.err.println("已跳过一条错误");
					e.printStackTrace();
				}
			}

			for (SoccerMatch match : matchList)
				System.out.println(match.getTypeName() + match.getTeam1Name()
						+ match.getTeam2Name());
			
			this.filter(matchList);
			return matchList;
		} catch (ParserException e) {
			e.printStackTrace();
			return new ArrayList<SoccerMatch>();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return new ArrayList<SoccerMatch>();
		}
	}

	public void filter(List<SoccerMatch> matchList) {
		new FilterHandler().handle(matchList);
		new JunkFilterHandler().handle(matchList);
		new ChannelFilterHandler().handle(matchList);
		new FocusHandler().handle(matchList);
	}
}
